﻿Imports System.Management
Imports System.IO
Imports Sunts.DataLayer.SQLite

Imports System.Data.SQLite


Public Module UDF
    Private Declare Function GetDiskFreeSpaceEx Lib "kernel32" Alias "GetDiskFreeSpaceExA" (ByVal lpDirectoryName As String, ByRef lpFreeBytesAvailableToCaller As Long, ByRef lpTotalNumberOfBytes As Long, ByRef lpTotalNumberOfFreeBytes As Long) As Long

    Public Function GetFreeSpace(ByVal Drive As String) As Long
        Dim TotalBytes As Long
        Dim FreeBytes As Long
        Dim FreeBytesAvailable As Long

        Try
            If GetDiskFreeSpaceEx(Drive, FreeBytesAvailable, TotalBytes, FreeBytes) > 0 Then
                Return CLng(((FreeBytes / 1024) / 1024))
            Else
                Throw New Exception("Invalid or unreadable drive")
            End If
        Catch ex As Exception
            Return Nothing
        Finally
            TotalBytes = Nothing
            FreeBytes = Nothing
            FreeBytesAvailable = Nothing
        End Try
    End Function

    Public Function CheckForVirtualMachines(ByVal HyperVHost As HyperVHost) As VirtualMachineCollection
        Dim VirtualMachineCollection As VirtualMachineCollection
        Dim ConnectionOptions As ConnectionOptions
        Dim ManagementScope As ManagementScope
        Dim VirtualMachine As VirtualMachine

        Try
            VirtualMachineCollection = New VirtualMachineCollection

            If HyperVHost.Hostname = "localhost" Then
                ManagementScope = New ManagementScope("root\virtualization")
           Else
                ConnectionOptions = New ConnectionOptions
                ConnectionOptions.Username = HyperVHost.Username
                ConnectionOptions.Password = HyperVHost.Password
                ManagementScope = New ManagementScope("\\" & HyperVHost.Hostname & "\root\virtualization", ConnectionOptions)
            End If


            Using ManagementObjectSearcher As New ManagementObjectSearcher(ManagementScope, New ObjectQuery("SELECT * FROM Msvm_ComputerSystem"))
                Using ManagementObjectCollection As ManagementObjectCollection = ManagementObjectSearcher.Get()
                    For Each ManagementObject As ManagementObject In ManagementObjectCollection
                        If ManagementObject("Caption").ToString.ToLower = "virtual machine" Then
                            VirtualMachine = New VirtualMachine
                            VirtualMachine.VirtualMachineName = ManagementObject("ElementName").ToString
                            VirtualMachine.VirtualMachineGuid = ManagementObject("Name").ToString
                            VirtualMachineCollection.Add(VirtualMachine)
                        End If
                    Next
                End Using
            End Using

            Return VirtualMachineCollection

        Catch ex As ManagementException
            If ex.ErrorCode = ManagementStatus.InvalidNamespace Then
                Throw New Exception("The virtualization namespace cannot be found." & _
                                     ControlChars.CrLf & _
                                     "Is this system running Hyper-V?")
            Else
                Throw New Exception("UDF: CheckForVirtualMachines: " & ex.Message)
            End If
        Catch ex As UnauthorizedAccessException
            Throw New Exception("There was an error logging on to the server, please verify your credentials")
        Catch ex As Exception
            Throw New Exception("UDF: CheckForVirtualMachines: " & ex.Message)
        Finally
            VirtualMachineCollection = Nothing
            ConnectionOptions = Nothing
            ManagementScope = Nothing
            VirtualMachine = Nothing
        End Try
    End Function

    Public Sub WriteToLogFile(ByVal msg As String, ByVal LogName As String)
        Try
            Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory & "\Logs\")
            Using FileStream As New FileStream(System.AppDomain.CurrentDomain.BaseDirectory & "\Logs\" & LogName, FileMode.Append, FileAccess.Write)
                Using StreamWriter As New StreamWriter(FileStream)
                    StreamWriter.WriteLine(Now() & ": " & msg)
                End Using
            End Using
        Catch ex As Exception
        End Try
    End Sub

    Public Class DatabaseCheck
        Public Property Exists As Boolean
        Public Property Location As String

        Public Sub New(ConnectionString As String)
            Me.Location = SQLiteDataLayer.ParseConnectionString(ConnectionString)
            If File.Exists(Me.Location) Then
                Me.Exists = True
            Else
                Me.Exists = False
            End If
        End Sub
    End Class

    Public Function ChangeConnectionString(ByVal connStringName As String, ByVal newValue As String) As Boolean
        Try
            Dim doc As XDocument = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)

            'Find all connection strings
            Dim query1 = From p In doc.Descendants("connectionStrings").Descendants()
      
            'Go throught each connection string elements find atribute specified by argument and replace its value with newVAlue
            For Each child As XElement In query1
                For Each atr As XAttribute In child.Attributes()
                    If atr.Name.LocalName = "name" AndAlso atr.Value = connStringName Then
                        If atr.NextAttribute IsNot Nothing AndAlso atr.NextAttribute.Name = "connectionString" Then
                            atr.NextAttribute.Value = newValue
                        End If
                    End If
                Next
            Next

            doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)

            Return True
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Return False
        End Try
    End Function

End Module
